﻿using DE_MVC_WyFy.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using MvcPaging;
using DE_MVC_WyFy.Areas.Administrator.Models;
namespace DE_MVC_WyFy.Areas.Administrator.Controllers
{
	public class ProductManagerController : Controller
	{
		//
		// GET: /Administrator/Product/

		public ActionResult Index(string key, int? page)
		{
			int total, pageSize = 5;
			int pageNumber = page ?? 1;
			IEnumerable<Product> db = Product.Objects.All().ToList();
			IEnumerable<Product> prod;
			if (!string.IsNullOrEmpty(key))
			{
				var temp = Product.Objects.Find(c => c.Name.Contains(key));
				//prod = temp.Skip((pageNumber - 1) * pageSize).Take(pageSize).ToList();
				prod = temp.ToPagedList(pageNumber, pageSize);

			}
			else

				prod = db.ToPagedList(pageNumber, pageSize);
			total = prod.Count();
			var pages = new PageInfo { PageSize = pageSize, TotalItem = total, Url = "Administrator/ProductManager", Current = pageNumber };
			ViewBag.Page = pages;
			return View(prod);
		}
		
		public ActionResult Edit(string id)
		{
			Product pro = Product.Objects.GetById(id);
			//Lấy Danh sách ProductType đổ vào DropdownList
			//Chú ý: ViewBag.ProductTypeID thì qua View ta sẽ gọi lại
			//Đặt tên ViewBag "ProductTypeID" để nó hiểu là thuộc tính trong ProductType

			var prodT = ProductType.Objects.All().ToList();
			ViewBag.ProductTypeID = new SelectList(prodT, "ProductTypeID", "ProductTypeName", pro.ProductTypeID);
			return View(pro);
		}
		[HttpPost]
		public ActionResult Edit(Product db)
		{
			if (ModelState.IsValid)
			{
				Product.Objects.InsertOrUpdate(db);
				return RedirectToAction("Index");
			}
			ViewBag.ProductTypeID = new SelectList(ProductType.Objects.All(), "ProductTypeID", "ProductTypeName", db.ProductTypeID);
			return View(db);
		}
		public ActionResult Create()
		{
			var prodT = ProductType.Objects.All().ToList();
			ViewBag.ProductTypeID = new SelectList(prodT, "ProductTypeID", "ProductTypeName");
			return View();
		}
		[HttpPost]
		public ActionResult Create(Product db)
		{
			var prodT = ProductType.Objects.All().ToList();
			ViewBag.ProductTypeID = new SelectList(prodT, "ProductTypeID", "ProductTypeName");
			return View(db);
		}
	}
}
